/****************************************************
          File Name:udpcl.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 26 Jan 2015 04:18:20 PM CST
*****************************************************/

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/ip.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>

#define SA  struct sockaddr
static socklen_t len = sizeof(struct sockaddr_in);

static void err(const char *s)
{
    perror(s);
    exit(errno);
}

int main(int argc, char *argv[])
{
    struct sockaddr_in client, server;
    int sockfd, fd;
    struct stat f_stat;
    int nfd;
    int res = 0;
    fd_set r_set;

    if(argc != 3)
    {
        fprintf(stderr, "%s ipaddr filename\n", argv[0]);
        exit(1);
    }
    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        err("socket");

    bzero(&server, len);

    server.sin_family = AF_INET;
    inet_pton(AF_INET, argv[1], &server.sin_addr.s_addr);
    server.sin_port = htons(8888);

    if(sendto(sockfd, argv[2], strlen(argv[2]) + 1, 0, (SA *)&server, len) == -1)
        err("sendto server");

    char filesize[20];
    if(recvfrom(sockfd, filesize, 20, 0, NULL, 0 ) == -1)
        err("recvfrom file size");

    char name[50];
    sprintf(name, "recv-%s", argv[2]);

    fd = open(name, O_CREAT|O_RDWR|O_APPEND, 00644);
    if(fd == -1)
        err("open");
    char buf[32765];
    bzero(buf, 32765);
    bzero(&client, len);
    size_t size = atol(filesize);
    size_t num = size / 32765;
    size_t den = size - (num * 32765);
    char rev[1] = {'0'};

    printf("------filesize = %s--------\n", filesize);
    nfd = sockfd + 1;
    for(;;)
    {
        FD_SET(sockfd, &r_set);
        res = select(nfd, &r_set, NULL, NULL, NULL);
        if(res == -1)
            err("select");
        else if(FD_ISSET(sockfd, &r_set))
        {
            if(num--)
            {
                recvfrom(sockfd, buf, 32765, 0, NULL, 0);
                write(fd, buf, 32765);
                sendto(sockfd, rev, 1, 0, (SA *)&server, len);  // inform server 
                FD_CLR(sockfd, &r_set);
            }
            else
                break;
        }
    }
    
    recvfrom(sockfd, buf, den, 0, NULL, 0);
    write(fd, buf, den);
    sendto(sockfd, rev, 1, 0, (SA *)&server, len);  // inform server 

    close(fd);

    printf("---------done----------\n");
}
